import wx
import wx.adv as adv
import os

from SqliteHandler import SqliteHandler
from DataTool import DataTool
from SqlDict import SqlDict

class DiaCreateBook(wx.Dialog):
    BaseInput = {0: {'分册名称':'', '分册类型':''},}
    BaseWidth = {0: [400, 90], 1: [80, 80, 80, 80],}
    BtnString = ["确定(&S)", "取消(&C)"]
    AdvInput = {
                '税率': {'施工单位增值税税率': 0.09, '材料增值税税率': 0.13, '服务费增值税税率': 0.06},
                '折扣': {'施工折扣': 1, '设计折扣': 1, '勘察折扣': 1, '监理折扣': 1,
                        '审计折扣': 1, '安全生产费折扣': 1, },
                '表二相关': {'施工场地距离': 35, '施工地点': '重庆', '特殊施工地区': '无', '大型机械调遣距离': 0, 
                            '大型机械吨位': 0},
                '表三相关': {'特殊区域': '', '特殊区域调整系数': 0,},
                '表四相关': {'材料运距': 0, },
                }
    Locations = ['北京', '天津', '上海', '重庆', '内蒙古', '广西', '西藏', '宁夏', '新疆', '河北', '山西', '辽宁',
                 '吉林', '黑龙江', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东',
                 '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海', '台湾', '香港', '澳门', '其他']
    Books = {'book1': '电源设备分册',
             'book2': '有线设备分册',
             'book3': '无线设备分册',
             'book4': '线路工程分册',
             'book5': '管道工程分册',}
    def __init__(self, parent, title, *args, **kwargs):
        super().__init__(parent, -1, title)
        
        self.path = kwargs.get('path')
        self.data = kwargs.get('data')
        self.Names = kwargs.get('names', [])
        self.ret = dict()
        self.MainSizer = wx.BoxSizer(orient=wx.VERTICAL)
        MainSizer = self.MainSizer
        BtnSizer = wx.BoxSizer(orient=wx.HORIZONTAL)
        self.AdvSizer = wx.BoxSizer(orient=wx.VERTICAL)
        AdvSizer = self.AdvSizer

        self.AdvIsShown = False

        self.InitData()
        self.InitBaseInput(MainSizer)
        self.InitAdv(AdvSizer)
        self.InitBtn(BtnSizer)

        MainSizer.Add(wx.StaticLine(self), 0,
                wx.EXPAND|wx.TOP|wx.BOTTOM, 0)
        MainSizer.Add(AdvSizer, 0, wx.EXPAND|wx.ALL, 5)
        MainSizer.Add(BtnSizer, 0, wx.EXPAND|wx.ALL, 5)
        
        self.SetSizer(MainSizer)
        MainSizer.Fit(self)
        MainSizer.SetSizeHints(self)

    def InitBaseInput(self, sizer):
        for row in self.BaseInput:
            thatsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
            for index, name in enumerate(self.BaseInput[row]):
                static = wx.StaticText(self, -1, name,)
                if '类型' in name:
                    choices = list(self.Books.values())
                    textctrl = wx.Choice(self, -1, choices=choices, name='TextCtrl' + name,)
                    textctrl.SetSelection(0)
                else:
                    textctrl = wx.TextCtrl(self, -1, size=(self.BaseWidth[row][index],-1), name='TextCtrl' + name,)
                thissizer = wx.BoxSizer(orient=wx.HORIZONTAL)
                thissizer.Add(static, 0, wx.ALL|wx.CENTRE, 5)
                thissizer.Add(textctrl, 0, wx.ALL|wx.CENTRE, 5)
                thatsizer.Add(thissizer,0, wx.ALL|wx.CENTRE, 0)

                self.ret[name] = ''

            sizer.Add(thatsizer, 0, wx.ALL|wx.CENTRE, 5)
        
        # 初始化数据
        for key in self.BaseInput[0]:
            Obj = self.FindWindowByName('TextCtrl' + key)
            if key == '分册类型':
                Index = Obj.FindString(self.data.get(key, '电源设备分册'))
                Obj.SetSelection(Index)
            else:
                Obj.Clear()
                Obj.write(self.data.get(key, ''))

    def InitBtn(self, sizer):
        for index, string in enumerate(self.BtnString):
            Btn = wx.Button(self, -1, string, name = 'btn' + string)
            if index == 0:
                sizer.Add((140,20), 1)
            sizer.Add(Btn, 0, wx.ALL|wx.EXPAND, 5)
            if index == 0:
                self.Bind(wx.EVT_BUTTON, self.OnSave, Btn)
            elif index == 1:
                self.Bind(wx.EVT_BUTTON, self.OnCancel, Btn)

    def InitAdv(self, sizer):
        for sizername in self.AdvInput:
            thatsizer = wx.StaticBoxSizer(wx.VERTICAL, self, sizername)
            for i in range((len(self.AdvInput[sizername]) - 1)//4 + 1):
                dictlen = len(self.AdvInput[sizername])
                base = (dictlen - 1)//3
                start = i * 3
                if i < base:
                    end = start + 3
                else:
                    end = start + (dictlen - 1) % 3 + 1
                thissizer = wx.BoxSizer(orient=wx.HORIZONTAL)
                keys = list(self.AdvInput[sizername].keys())[start: end]
                values = list(self.AdvInput[sizername].values())[start: end]
                for index, name in enumerate(keys):
                    static = wx.StaticText(self, -1, name,)
                    if name == '施工地点' or name == '特殊施工地区':
                        if name == '施工地点':
                            choices = self.Locations
                        elif name == '特殊施工地区':
                            choices = self.speclocations
                        textctrl = wx.Choice(self, -1, choices=choices, name='TextCtrl' + name,)
                        stringindex = textctrl.FindString(values[index])
                        if stringindex == wx.NOT_FOUND:
                            textctrl.SetSelection(0)
                        else:
                            textctrl.SetSelection(stringindex)
                    else:
                        textctrl = wx.TextCtrl(self, -1, size=(50,-1), name='TextCtrl' + name, value=str(values[index]))
                    thissizer.Add(static, 0, wx.ALL|wx.ALIGN_CENTER, 5)
                    thissizer.Add(textctrl, 1, wx.ALL|wx.CENTRE|wx.SHAPED, 5)

                    self.ret[name] = ''
                    # if base == i and index == end - start - 1:
                    #     rate = 4 - end - start
                    #     thissizer.Add((50, -1), rate, wx.ALL|wx.CENTRE|wx.SHAPED, 5)
                thatsizer.Add(thissizer,1, wx.ALL|wx.CENTRE|wx.EXPAND, 0)
            sizer.Add(thatsizer, 0, wx.ALL|wx.CENTRE|wx.EXPAND, 5)

    def InitData(self):
        path = os.path.join(self.path, 'rate.db')
        conn = SqliteHandler(path)
        self.speclocations = conn.select('spicfees_locations', flag='list')
        self.speclocations = [i[1] for i in self.speclocations]
        self.speclocations.insert(0, '无')

        for key in self.data:
            DataTool.feefillin(self.AdvInput, key, self.data[key])


    def OnCancel(self, event):
        self.EndModal(retCode=5101)

    def ShowModal(self):
        ret = super().ShowModal()
        if ret == 5101:
            return ret
        elif ret == 1:
            return self.ret
        else:
            return 5101

    def OnSave(self, event):
        waringemptnames = ['项目名称', '建设单位', '预算编制人', '设计负责人', '审核负责人']
        waringnumnames = ['施工单位增值税税率', '材料增值税税率', '服务费增值税税率', '施工折扣', 
                          '设计折扣', '勘察折扣', '监理折扣', '审计折扣', '安全生产费折扣', 
                          '施工场地距离', '大型机械调遣距离', '大型机械吨位' ,'特殊区域调整系数', 
                          '材料运距']
        waringemptmessage = '数据不能为空！'
        waringnummessage = '填入数据必须为数字！'

        names = list(self.ret.keys())
        for index, name in enumerate(names):
            obj = self.FindWindowByName('TextCtrl' + name)
            if '时间' in name:
                text = obj.GetValue().FormatDate()
            elif name == '施工地点' or name == '特殊施工地区' or name == '分册类型':
                text = obj.GetString(obj.GetSelection())
            else:
                text = obj.GetLineText(0)
            if name in waringemptnames and text == '':
                dia = wx.MessageDialog(self, '"' + name + '"' + waringemptmessage,
                    caption='警告',style=wx.OK|wx.ICON_WARNING)
                dia.ShowModal()
                dia.Destroy()
                return
            if name in waringnumnames and not DataTool.isnum(text):
                dia = wx.MessageDialog(self, '"' + name + '"' + waringnummessage,
                    caption='警告',style=wx.OK|wx.ICON_WARNING)
                dia.ShowModal()
                dia.Destroy()
                return
            self.ret[name] = text

        if self.ret['分册名称'] in self.Names:
            wx.MessageBox('分册名称不能重复!'
                , '警告!',style=wx.OK|wx.ICON_WARNING)
            return

        self.EndModal(retCode=1)



if __name__ == "__main__":

    BASE_DIR = os.path.dirname(os.path.abspath(__file__))

    class MyFrame(wx.Frame):
        def __init__(self):
            super().__init__(None, -1, 'haha', size=(200, 100))
            btn = wx.Button(self, -1, 'baba', size=(10, 10))
            self.Bind(wx.EVT_BUTTON, self.OnClick, btn)

        def OnClick(self, event):
            # modal = DiaTable2add(self, 'baba').ShowModal()
            data = {'分册名称': 'qwe', '分册类型': '线路工程分册', '施工单位增值税税率': '1', 
                    '材料增值税税率': '2', '服务费增值税税率': '36', '施工折扣': '4', 
                    '设计折扣': '5', '勘察折扣': '6', '监理折扣': '7', '审计折扣': '8', 
                    '安全生产费折扣': '9', '施工场地距离': '315', '施工地点': '山东', '特殊施工地区': '沙漠', 
                    '大型机械调遣距离': '11', '大型机械吨位': '12', '特殊区域': '111', '特殊区域调整系数': '13', 
                    '材料运距': '14'}
            dia = DiaCreateBook(self, 'haha', path=os.path.join(BASE_DIR, 'db'), data=data)
            modal = dia.ShowModal()
            print(modal)
            dia.Destroy()

    app = wx.App()
    MyFrame().Show()
    app.MainLoop()